var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
const carts = require('../../utils/cart')
const config = require('../../config/config')
var qqmapsdk;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        shops: [
        ],
        selectedIndex: 0,
        selectedCategory: '',
        swiperList: [
           '/images/banner/8283.jpg_wh300.jpg',
            '/images/banner/8279.jpg_wh300.jpg',
            '/images/banner/9227.jpg_wh300.jpg',
            '/images/banner/0383.jpg_wh300.jpg'
        ],
        location: '',
        menuHeight: 0,
        tops: [], //高度
        shopListTop: 0,
        popupVisible: false, //控制弹窗显示与隐藏
        popupDetail: '',
        defaultNum: 0
    },
    //从服务器获取商品
    getGoods(){
        wx.showLoading();
        wx.request({
          url: `${config.server}/goods/getAllShops`,
          success:res=>{
              if(res.data.status=='success'){
                 this.setData({
                     shops:res.data.data,
                     selectedCategory:res.data.data[0].category
                 })
                 this.getTops()
                 console.log(this.data.tops);
              }else{
                  wx.showToast({
                    title: '商品获取失败',
                    icon:'error'
                  })
              }
          },
          fail:err=>{
            wx.showToast({
                title: '商品获取失败',
                icon:'error'
              })
          }
        })
        wx.hideLoading()
    },
    // popup加入购物车
    cart(e) {
        // console.log(e);
        const {
            detail
        } = e.detail
        console.log(detail);
        carts.add(detail)
        // 隐藏商品弹窗
        this.setData({
            popupVisible: false
        })
    },
    // 首页中点击加号加入购物车
    addcart(e) {
        // console.log(e);
        const {
            detail
        } = e.currentTarget.dataset
        detail.num = 1
        carts.add(detail)
        // console.log(wx.getStorageSync('carts'));
    },
    // 首页中点击减号加入购物车
    minuscart(e) {
        const {
            detail
        } = e.currentTarget.dataset
        console.log('减号');
        detail.num = -1
        carts.add(detail)
        // console.log(wx.getStorageSync('carts'));
    },

    //弹出对话框 
    selectGoods(e) {
        // console.log(e);
        const {
            detail
        } = e.currentTarget.dataset
        if (detail.goods_count === 0) {
            wx.showToast({
                title: '商品已售罄',
                icon: 'error'
            })
        } else {
            this.setData({
                popupVisible: true,
                popupDetail: detail
            })
        }
    },
    //商品列表滚动事件
    shopListScroll(e) {
        const {
            scrollTop
        } = e.detail
        const {
            tops
        } = this.data
        for (let i = 0; i < tops.length; i++) {
            if (scrollTop > tops[i] && scrollTop < tops[i + 1]) {
                this.setData({
                    selectedIndex: i,
                    selectedCategory: this.data.shops[i].category
                })
            }
        }
    },
    // 获取商品分类的高度
    getTops() {
        return new Promise((resolve, reject) => {
            console.log('getTops')
            wx.createSelectorQuery().selectAll('.shop_list_item').boundingClientRect(res => {
                let tops = [0]
                res.forEach((item, i) => {
                    if (i == 0) {
                        tops.push(item.height) //tops[1]
                    } else {
                        tops.push(tops[i] + item.height)
                    }
                })
                // const height = res.reduce((sum, item) => {
                //     return sum = sum + item.height
                // }, 0)
                // console.log(height);
                this.setData({
                    tops:tops
                })
                resolve('ok')
            }).exec()
        })
    },
    //点击分类列表展示不同的信息
    selectedCategory(e) {
        const {
            index
        } = e.currentTarget.dataset
        const {
            tops
        } = this.data
        this.setData({
            selectedIndex: index,
            selectedCategory: this.data.shops[index].category,
            shopListTop: tops[index],
        })
    },
    //设置商品列表高度
    setHeight() {
        const windowHeight = wx.getSystemInfoSync().windowHeight
        const dpr = wx.getSystemInfoSync().pixelRatio
        wx.createSelectorQuery().select('.swiper').boundingClientRect(e => {
            this.setData({
                menuHeight: windowHeight - e.height - 60 / dpr
            })
        }).exec()
    },
    myLocation() {
        wx.getLocation({
            type: 'gcj02',
            success: result => {
                //   console.log(result)
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: result.latitude,
                        longitude: result.longitude
                    },
                    success: res => {
                        this.setData({
                            location: res.result.address
                        })
                    }
                })
            }
        })
    },
    // 已售完
    soldOut() {
        wx.showToast({
            title: '已售罄',
            icon: 'error'
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
            key: 'XA4BZ-UXSLD-YHZ4U-P4XTC-Y4OXJ-WZBEH'
        });
        this.myLocation()
        this.setHeight()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    async onReady() {
      
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 设置徽章
        carts.setBadge()
        this.getGoods()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.setData({
            defaultNum: 0
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})